﻿using Bystd.Geo.Converters;
using Bystd.Geo.Geometries;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bystd.Geo.GeoParsers.SpatiaLite
{
    public class GeometryReader:BaseBytes
    {
        private byte[] buffer = null;
        private int offset = 0;
        private int srid = 0;
        private BitExtensions bitConvert = null;
        private Wkb.GeometryReader wkbReader = null;

        public Coordinate Min { get; set; }

        public Coordinate Max { get; set; }

        public GeometryReader(byte [] buffer,int offset=0)
        {
            this.buffer = buffer;
            this.offset = offset;
            ByteOrder byteOrder = buffer[1] == 1 ? ByteOrder.LittleEndian : ByteOrder.BigEndian;
            bitConvert = new BitExtensions(byteOrder);
            wkbReader = new  Wkb.GeometryReader(buffer, offset+39, byteOrder);
        }

        public Geometry Reader()
        {
            if ((buffer.Length - offset) < 45)
                throw new Exception("invalid blob geometry");

            if (buffer[offset] != (byte)BlobMark.MARK_START)
                throw new Exception("invalid start signature");

            if (buffer[buffer.Length - 1] != (byte)BlobMark.MARK_END)
                throw new Exception("invalid end signature");

            if (buffer[offset + 38] != (byte)BlobMark.MARK_MBR)
                throw new Exception("invalid MBR signature");

            Min = new Coordinate(bitConvert.ToDouble(buffer, offset + 6),
                bitConvert.ToDouble(buffer, offset + 14));
            Max = new Coordinate(bitConvert.ToDouble(buffer, offset + 22),
                bitConvert.ToDouble(buffer, offset + 30));

            srid = bitConvert.ToInt32(buffer, offset + 2);
            var geo= wkbReader.Reader();
            geo.SRID = srid;

            return geo;
        }
    }
}
